# -*- coding: utf-8 -*-
"""
时间计算标签页
提供时间计算功能的用户界面
"""

from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QGridLayout,
                            QLabel, QPushButton, QTimeEdit, QSpinBox, QComboBox,
                            QTextEdit, QFrame, QGroupBox, QButtonGroup, QRadioButton,
                            QApplication, QMessageBox, QScrollArea, QCheckBox)
from PyQt5.QtCore import Qt, QTime, pyqtSignal, QTimer
from PyQt5.QtGui import QFont

import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

from core.time_calculator import TimeCalculator


class TimeCalculatorTab(QWidget):
    """时间计算标签页"""
    
    # 信号定义
    calculation_completed = pyqtSignal(dict)
    
    def __init__(self, history_manager=None):
        super().__init__()
        self.calculator = TimeCalculator()
        self.history_manager = history_manager
        self.init_ui()
        self.connect_signals()
    
    def init_ui(self):
        """初始化用户界面"""
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(20, 20, 20, 20)
        main_layout.setSpacing(20)
        
        # 创建水平分割布局
        content_layout = QHBoxLayout()
        content_layout.setSpacing(25)
        
        # 左侧：输入和控制区域
        left_widget = QWidget()
        left_layout = QVBoxLayout(left_widget)
        left_layout.setContentsMargins(0, 0, 0, 0)
        left_layout.setSpacing(20)
        
        # 创建时间加减区域
        time_add_group = self.create_time_add_group()
        left_layout.addWidget(time_add_group)
        
        # 创建时间间隔计算区域
        interval_group = self.create_interval_group()
        left_layout.addWidget(interval_group)
        
        # 创建操作按钮区域
        button_group = self.create_button_group()
        left_layout.addWidget(button_group)
        
        left_layout.addStretch()
        
        # 右侧：结果显示区域
        result_group = self.create_result_group()
        
        # 设置左右比例 (左侧40%，右侧60%)
        content_layout.addWidget(left_widget, 2)  # 左侧占2份
        content_layout.addWidget(result_group, 3)  # 右侧占3份
        
        main_layout.addLayout(content_layout)
    
    def create_time_add_group(self):
        """创建时间加减区域"""
        group_box = QGroupBox("时间加减计算")
        group_box.setFont(QFont("Microsoft YaHei", 11, QFont.Bold))
        group_box.setMinimumHeight(180)
        group_box.setStyleSheet("""
            QGroupBox {
                font-weight: bold;
                border: 2px solid #dee2e6;
                border-radius: 8px;
                margin-top: 10px;
                padding-top: 15px;
                background-color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                left: 15px;
                padding: 0 8px 0 8px;
                color: #495057;
                background-color: #ffffff;
            }
        """)
        
        layout = QGridLayout(group_box)
        layout.setSpacing(15)
        layout.setContentsMargins(25, 30, 25, 25)
        
        # 基础时间选择
        layout.addWidget(QLabel("基础时间:"), 0, 0)
        self.base_time_edit = QTimeEdit()
        self.base_time_edit.setTime(QTime.currentTime())
        self.base_time_edit.setDisplayFormat("HH:mm:ss")
        self.base_time_edit.setMinimumHeight(30)
        layout.addWidget(self.base_time_edit, 0, 1)
        
        # 当前时间按钮
        now_btn = QPushButton("当前时间")
        now_btn.setMinimumHeight(30)
        now_btn.clicked.connect(lambda: self.base_time_edit.setTime(QTime.currentTime()))
        layout.addWidget(now_btn, 0, 2)
        
        # 加减选择
        layout.addWidget(QLabel("操作类型:"), 1, 0)
        
        self.time_calc_type_group = QButtonGroup()
        
        calc_type_layout = QHBoxLayout()
        calc_type_layout.setSpacing(20)
        
        self.time_add_radio = QRadioButton("加上")
        self.time_add_radio.setChecked(True)
        self.time_add_radio.setMinimumHeight(25)
        calc_type_layout.addWidget(self.time_add_radio)
        
        self.time_subtract_radio = QRadioButton("减去")
        self.time_subtract_radio.setMinimumHeight(25)
        calc_type_layout.addWidget(self.time_subtract_radio)
        
        self.time_calc_type_group.addButton(self.time_add_radio, 1)
        self.time_calc_type_group.addButton(self.time_subtract_radio, -1)
        
        calc_type_layout.addStretch()
        layout.addLayout(calc_type_layout, 1, 1, 1, 2)
        
        # 时间数值输入
        layout.addWidget(QLabel("小时:"), 2, 0)
        self.hours_spin = QSpinBox()
        self.hours_spin.setRange(0, 23)
        self.hours_spin.setValue(1)
        self.hours_spin.setMinimumHeight(30)
        layout.addWidget(self.hours_spin, 2, 1)
        
        layout.addWidget(QLabel("分钟:"), 2, 2)
        self.minutes_spin = QSpinBox()
        self.minutes_spin.setRange(0, 59)
        self.minutes_spin.setValue(0)
        self.minutes_spin.setMinimumHeight(30)
        layout.addWidget(self.minutes_spin, 2, 3)
        
        layout.addWidget(QLabel("秒:"), 2, 4)
        self.seconds_spin = QSpinBox()
        self.seconds_spin.setRange(0, 59)
        self.seconds_spin.setValue(0)
        self.seconds_spin.setMinimumHeight(30)
        layout.addWidget(self.seconds_spin, 2, 5)
        
        return group_box
    
    def create_interval_group(self):
        """创建时间间隔计算区域"""
        group_box = QGroupBox("时间间隔计算")
        group_box.setFont(QFont("Microsoft YaHei", 11, QFont.Bold))
        group_box.setMinimumHeight(120)
        group_box.setStyleSheet("""
            QGroupBox {
                font-weight: bold;
                border: 2px solid #dee2e6;
                border-radius: 8px;
                margin-top: 10px;
                padding-top: 15px;
                background-color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                left: 15px;
                padding: 0 8px 0 8px;
                color: #495057;
                background-color: #ffffff;
            }
        """)
        
        layout = QGridLayout(group_box)
        layout.setSpacing(15)
        layout.setContentsMargins(25, 30, 25, 25)
        
        # 开始时间
        layout.addWidget(QLabel("开始时间:"), 0, 0)
        self.start_time_edit = QTimeEdit()
        self.start_time_edit.setTime(QTime(9, 0, 0))
        self.start_time_edit.setDisplayFormat("HH:mm:ss")
        self.start_time_edit.setMinimumHeight(30)
        layout.addWidget(self.start_time_edit, 0, 1)
        
        # 结束时间
        layout.addWidget(QLabel("结束时间:"), 0, 2)
        self.end_time_edit = QTimeEdit()
        self.end_time_edit.setTime(QTime(17, 0, 0))
        self.end_time_edit.setDisplayFormat("HH:mm:ss")
        self.end_time_edit.setMinimumHeight(30)
        layout.addWidget(self.end_time_edit, 0, 3)
        
        # 跨天选择
        self.cross_day_check = QCheckBox("跨天计算")
        self.cross_day_check.setMinimumHeight(25)
        layout.addWidget(self.cross_day_check, 0, 4)
        
        return group_box
    
    def create_button_group(self):
        """创建按钮区域"""
        frame = QFrame()
        frame.setMinimumHeight(60)
        layout = QHBoxLayout(frame)
        layout.setSpacing(15)
        layout.setContentsMargins(20, 10, 20, 10)
        
        # 时间计算按钮
        self.time_calculate_btn = QPushButton("🕐 时间计算")
        self.time_calculate_btn.setMinimumHeight(45)
        self.time_calculate_btn.setMinimumWidth(120)
        self.time_calculate_btn.setStyleSheet("""
            QPushButton {
                background-color: #007bff;
                color: white;
                border: none;
                border-radius: 8px;
                font-size: 13px;
                font-weight: bold;
                padding: 8px 16px;
            }
            QPushButton:hover {
                background-color: #0056b3;
            }
            QPushButton:pressed {
                background-color: #004085;
            }
        """)
        layout.addWidget(self.time_calculate_btn)
        
        # 间隔计算按钮
        self.interval_calculate_btn = QPushButton("⏱️ 间隔计算")
        self.interval_calculate_btn.setMinimumHeight(45)
        self.interval_calculate_btn.setMinimumWidth(120)
        self.interval_calculate_btn.setStyleSheet("""
            QPushButton {
                background-color: #28a745;
                color: white;
                border: none;
                border-radius: 8px;
                font-size: 13px;
                font-weight: bold;
                padding: 8px 16px;
            }
            QPushButton:hover {
                background-color: #1e7e34;
            }
            QPushButton:pressed {
                background-color: #155724;
            }
        """)
        layout.addWidget(self.interval_calculate_btn)
        
        # 当前时间按钮
        current_time_btn = QPushButton("🕒 当前时间")
        current_time_btn.setMinimumHeight(45)
        current_time_btn.setMinimumWidth(120)
        current_time_btn.setStyleSheet("""
            QPushButton {
                background-color: #17a2b8;
                color: white;
                border: none;
                border-radius: 8px;
                font-size: 13px;
                font-weight: bold;
                padding: 8px 16px;
            }
            QPushButton:hover {
                background-color: #117a8b;
            }
        """)
        current_time_btn.clicked.connect(self.show_current_time)
        layout.addWidget(current_time_btn)
        
        layout.addStretch()
        
        # 清空按钮
        clear_btn = QPushButton("🗑️ 清空")
        clear_btn.setMinimumHeight(45)
        clear_btn.setMinimumWidth(100)
        clear_btn.setStyleSheet("""
            QPushButton {
                background-color: #6c757d;
                color: white;
                border: none;
                border-radius: 8px;
                font-size: 12px;
                padding: 8px 16px;
            }
            QPushButton:hover {
                background-color: #545b62;
            }
        """)
        clear_btn.clicked.connect(self.clear_inputs)
        layout.addWidget(clear_btn)
        
        # 复制结果按钮
        copy_btn = QPushButton("📋 复制结果")
        copy_btn.setMinimumHeight(45)
        copy_btn.setMinimumWidth(120)
        copy_btn.setStyleSheet("""
            QPushButton {
                background-color: #17a2b8;
                color: white;
                border: none;
                border-radius: 8px;
                font-size: 12px;
                padding: 8px 16px;
            }
            QPushButton:hover {
                background-color: #117a8b;
            }
        """)
        copy_btn.clicked.connect(self.copy_result)
        layout.addWidget(copy_btn)
        
        return frame
    
    def create_result_group(self):
        """创建结果显示区域"""
        group_box = QGroupBox("计算结果")
        group_box.setFont(QFont("Microsoft YaHei", 11, QFont.Bold))
        group_box.setMinimumHeight(500)
        group_box.setStyleSheet("""
            QGroupBox {
                font-weight: bold;
                border: 2px solid #dee2e6;
                border-radius: 8px;
                margin-top: 10px;
                padding-top: 15px;
                background-color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                left: 15px;
                padding: 0 8px 0 8px;
                color: #495057;
                background-color: #ffffff;
            }
        """)
        
        layout = QVBoxLayout(group_box)
        layout.setContentsMargins(25, 30, 25, 25)
        layout.setSpacing(15)
        
        self.result_text = QTextEdit()
        self.result_text.setReadOnly(True)
        self.result_text.setFont(QFont("Microsoft YaHei", 11))
        self.result_text.setMinimumHeight(420)
        self.result_text.setStyleSheet("""
            QTextEdit {
                background-color: #f8f9fa;
                border: 2px solid #e9ecef;
                border-radius: 8px;
                padding: 15px;
                line-height: 1.6;
                color: #495057;
            }
            QTextEdit:focus {
                border-color: #007bff;
                background-color: #ffffff;
            }
        """)
        self.result_text.setPlaceholderText("时间计算结果将在这里显示...\n\n提示：\n• 设置基础时间\n• 选择要加减的时间\n• 点击时间计算按钮")
        layout.addWidget(self.result_text)
        
        return group_box
    
    def connect_signals(self):
        """连接信号和槽"""
        self.time_calculate_btn.clicked.connect(self.perform_time_calculation)
        self.interval_calculate_btn.clicked.connect(self.calculate_time_interval)
        self.calculation_completed.connect(self.display_result)
    
    def perform_time_calculation(self):
        """执行时间计算"""
        try:
            base_time = self.base_time_edit.time().toPyTime()
            hours = self.hours_spin.value()
            minutes = self.minutes_spin.value()
            seconds = self.seconds_spin.value()
            
            # 检查加减类型
            if self.time_subtract_radio.isChecked():
                hours = -hours
                minutes = -minutes
                seconds = -seconds
            
            result = self.calculator.add_time(base_time, hours, minutes, seconds)
            self.calculation_completed.emit(result)
            
            # 添加到历史记录
            if self.history_manager:
                input_data = {
                    'base_time': str(base_time),
                    'hours': hours if not self.time_subtract_radio.isChecked() else -hours,
                    'minutes': minutes if not self.time_subtract_radio.isChecked() else -minutes,
                    'seconds': seconds if not self.time_subtract_radio.isChecked() else -seconds,
                    'operation': "减去" if self.time_subtract_radio.isChecked() else "加上"
                }
                self.history_manager.add_calculation_record("时间计算", input_data, result)
            
        except Exception as e:
            QMessageBox.critical(self, "计算错误", f"时间计算过程中出现错误:\n{str(e)}")
    
    def calculate_time_interval(self):
        """计算时间间隔"""
        try:
            start_time = self.start_time_edit.time().toPyTime()
            end_time = self.end_time_edit.time().toPyTime()
            same_day = not self.cross_day_check.isChecked()
            
            result = self.calculator.calculate_time_interval(start_time, end_time, same_day)
            self.display_interval_result(result)
            
            # 添加到历史记录
            if self.history_manager:
                input_data = {
                    'start_time': str(start_time),
                    'end_time': str(end_time),
                    'cross_day': self.cross_day_check.isChecked()
                }
                self.history_manager.add_calculation_record("时间间隔计算", input_data, result)
            
        except Exception as e:
            QMessageBox.critical(self, "间隔计算错误", f"时间间隔计算过程中出现错误:\n{str(e)}")
    
    def show_current_time(self):
        """显示当前时间信息"""
        try:
            result = self.calculator.get_current_time_info()
            self.display_current_time_result(result)
            
        except Exception as e:
            QMessageBox.critical(self, "获取时间错误", f"获取当前时间信息时出现错误:\n{str(e)}")
    
    def display_result(self, result):
        """显示时间计算结果"""
        try:
            cross_day_info = ""
            if result['is_next_day']:
                cross_day_info = f"\n⚠️ 注意: 结果时间为次日 {result['result_date']}"
            elif result['is_prev_day']:
                cross_day_info = f"\n⚠️ 注意: 结果时间为前日 {result['result_date']}"
            
            result_text = f"""
═══════════════════════════════════════
⏰ 时间计算结果
═══════════════════════════════════════

🕐 基础时间: {result['formatted_base']}
🎯 结果时间: {result['formatted_result']}

📊 详细信息:
• 24小时制: {result['formatted_result']}
• 12小时制: {result['result_12hour']}
• 时间变化: {'+' if result['total_seconds_added'] >= 0 else ''}{result['hours_added']}小时{result['minutes_added']}分钟{result['seconds_added']}秒
• 总秒数变化: {result['total_seconds_added']}秒{cross_day_info}

💡 提示: 结果时间为 {result['formatted_result']}
            """
            
            self.result_text.setPlainText(result_text.strip())
            
        except Exception as e:
            self.result_text.setPlainText(f"显示结果时出现错误: {str(e)}")
    
    def display_interval_result(self, result):
        """显示时间间隔结果"""
        try:
            cross_day_info = ""
            if result['is_cross_day']:
                cross_day_info = "\n📅 跨天计算: 是"
            
            result_text = f"""
═══════════════════════════════════════
⏱️ 时间间隔计算结果
═══════════════════════════════════════

🕐 开始时间: {result['formatted_start']}
🕐 结束时间: {result['formatted_end']}

📊 间隔统计:
• 总时长: {result['interval_display']}
• 总小时数: {result['total_hours']:.2f}小时
• 总分钟数: {result['total_minutes']}分钟
• 总秒数: {result['total_seconds']}秒{cross_day_info}

💡 提示: 两个时间相差 {result['interval_display']}
            """
            
            self.result_text.setPlainText(result_text.strip())
            
        except Exception as e:
            self.result_text.setPlainText(f"显示间隔结果时出现错误: {str(e)}")
    
    def display_current_time_result(self, result):
        """显示当前时间信息"""
        try:
            result_text = f"""
═══════════════════════════════════════
🕒 当前时间信息
═══════════════════════════════════════

📅 完整时间: {result['full_datetime']}
🕐 24小时制: {result['formatted_24h']}
🕐 12小时制: {result['formatted_12h']}

📊 详细信息:
• 时区: {result['timezone']}
• 时间戳: {int(result['timestamp'])}
• UTC时间: {result['utc_formatted']}
• 小时: {result['hour']}
• 分钟: {result['minute']}
• 秒: {result['second']}

💡 提示: 当前为北京时间
            """
            
            self.result_text.setPlainText(result_text.strip())
            
        except Exception as e:
            self.result_text.setPlainText(f"显示当前时间时出现错误: {str(e)}")
    
    def copy_result(self):
        """复制结果到剪贴板"""
        result_text = self.result_text.toPlainText()
        if result_text:
            clipboard = QApplication.clipboard()
            clipboard.setText(result_text)
            
            # 创建一个浮动的成功提示
            self.show_floating_tip("✅ 复制成功！", "#28a745")
            
        else:
            # 没有结果时弹窗提醒
            QMessageBox.warning(self, "提示", "⚠️ 没有可复制的结果\n\n请先进行计算后再复制结果。")
    
    def show_floating_tip(self, message, color):
        """显示浮动提示"""
        from PyQt5.QtCore import QTimer
        from PyQt5.QtWidgets import QFrame
        
        # 创建卡片式提示框
        tip_frame = QFrame(self)
        tip_frame.setFrameStyle(QFrame.NoFrame)
        
        # 使用淡绿色背景
        tip_frame.setStyleSheet("""
            QFrame {
                background-color: rgba(212, 237, 218, 0.95);
                border: 1px solid rgba(40, 167, 69, 0.3);
                border-radius: 12px;
            }
        """)
        
        # 创建布局
        layout = QHBoxLayout(tip_frame)
        layout.setContentsMargins(16, 12, 16, 12)
        layout.setSpacing(12)
        
        # 创建圆形图标
        icon_label = QLabel("✓", tip_frame)
        icon_label.setStyleSheet("""
            QLabel {
                background-color: #28a745;
                color: white;
                border-radius: 15px;
                font-size: 14px;
                font-weight: bold;
                min-width: 30px;
                max-width: 30px;
                min-height: 30px;
                max-height: 30px;
            }
        """)
        icon_label.setAlignment(Qt.AlignCenter)
        
        # 创建文字标签
        text_label = QLabel("复制成功", tip_frame)
        text_label.setStyleSheet("""
            QLabel {
                color: #155724;
                font-size: 14px;
                font-weight: bold;
                background: transparent;
                border: none;
            }
        """)
        
        layout.addWidget(icon_label)
        layout.addWidget(text_label)
        
        # 调整框架大小
        tip_frame.adjustSize()
        tip_frame.setFixedSize(tip_frame.sizeHint())
        
        # 定位在应用的上半部分中央
        parent_rect = self.rect()
        tip_x = (parent_rect.width() - tip_frame.width()) // 2
        tip_y = parent_rect.height() // 5  # 放在上1/5位置
        tip_frame.move(tip_x, tip_y)
        
        # 显示提示框
        tip_frame.show()
        tip_frame.raise_()  # 确保在最顶层
        
        # 2秒后自动消失
        QTimer.singleShot(2000, tip_frame.deleteLater)
    
    def clear_inputs(self):
        """清空输入"""
        self.base_time_edit.setTime(QTime.currentTime())
        self.start_time_edit.setTime(QTime(9, 0, 0))
        self.end_time_edit.setTime(QTime(17, 0, 0))
        self.hours_spin.setValue(1)
        self.minutes_spin.setValue(0)
        self.seconds_spin.setValue(0)
        self.time_add_radio.setChecked(True)
        self.cross_day_check.setChecked(False)
        self.result_text.clear()
    
    def clear_all(self):
        """清空所有内容"""
        self.clear_inputs()
